package esb.chapter3;
import javax.annotation.Resource;
import javax.jbi.component.ComponentContext;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.jbi.servicedesc.ServiceEndpoint;
import javax.xml.namespace.QName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.servicemix.MessageExchangeListener;

import esb.util.framework.JiBXUtil;

public class SimpleTransformerBean implements MessageExchangeListener {

    private static Log log = LogFactory.getLog(SimpleTransformerBean.class);

    @Resource
    private DeliveryChannel channel;

    @Resource
    private ComponentContext compContext;

    public void onMessageExchange(MessageExchange exchange)
            throws MessagingException {
        try {
            if (exchange.getStatus() != ExchangeStatus.ACTIVE)
                return;

            Person person = (Person) JiBXUtil.unmarshalDocument(exchange
                    .getMessage("in").getContent(), Person.class);
            log.info("received person " + person.getFirstName() + " " + person.getLastName());
            person.setFirstName("John");
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);

            ServiceEndpoint targetEndpoint = compContext.getEndpoint(new QName(
                    "http://opensourceesb/chapter3/", "JMSProviderService"),
                    "outQueueWriter");
            MessageExchange exch = channel.createExchangeFactory(targetEndpoint)
                    .createInOnlyExchange();
            NormalizedMessage normalizedMsg = exch.createMessage();
            normalizedMsg.setContent(JiBXUtil.marshalDocument(person, "UTF-8"));
            exch.setMessage(normalizedMsg, "in");
            channel.send(exch);
        } catch (Exception e) {
            log.error("JBI bean exception", e);
            throw new MessagingException(
                    "Error transforming object to or from XML");
        }
    }
}
